package com.hnkywl.sts.dao.base;

import com.hnkywl.sts.entity.base.Dxpz;
import com.hnkywl.sts.util.StringFormat;
import net.ruixin.orm.hibernate.SimpleHibernateTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.stereotype.Repository;

import java.sql.CallableStatement;
import java.sql.SQLException;
import java.sql.Types;

/**
 * Created with IntelliJ IDEA.
 * User: xx
 * Date: 13-6-19
 * Time: 下午11:53
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class ZddxDao extends SimpleHibernateTemplate<Dxpz, Long> {
    private static final String PACKAGE = "BB_GYLWL_DX";

    //短信：黑色金属现货库存X吨（本部X，上海X，合肥X。。。）；
    private static final String KC = PACKAGE + ".BB_GYLWL_DX_KC";

    //今日采购额X（月累计X）今日销售额X（月累计X）
    private static final String CGXS = PACKAGE + ".BB_GYLWL_DX_CGXS";

    //今日财务收X（现汇X，银票X、商票X） 付X（现汇X，银票X、商票X）
    private static final String CW = PACKAGE + ".BB_GYLWL_DX_CW";

    /**
     * 短信：黑色金属现货库存X吨（本部X，上海X，合肥X。。。）；
     */
    public String[] getKc() throws SQLException {
        CallableStatement callableStatement = getCallable(StringFormat.format("{call {0}(?)}", KC));
        return getResult(callableStatement);
    }

    /**
     * 今日采购额X（月累计X）今日销售额X（月累计X）
     */
    public String[] getCgXs() throws SQLException {
        CallableStatement callableStatement = getCallable(StringFormat.format("{call {0}(?)}", CGXS));
        return getResult(callableStatement);
    }

    /**
     * 今日财务收X（现汇X，银票X、商票X）付X（现汇X，银票X、商票X）
     */
    public String[] getCw() throws SQLException {
        CallableStatement callableStatement = getCallable(StringFormat.format("{call {0}(?)}", CW));
        return getResult(callableStatement);
    }


    /**
     * 调用存储过程
     *
     * @param fn
     * @return
     * @throws SQLException
     */
    private CallableStatement getCallable(String fn) throws SQLException {
        return SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection().prepareCall(fn);
    }

    /**
     * 获取返回结果
     *
     * @param callableStatement
     * @return
     * @throws SQLException
     */
    private String[] getResult(CallableStatement callableStatement) throws SQLException {
        String strRet = "";
        callableStatement.registerOutParameter(1, Types.VARCHAR);
        if (callableStatement.executeUpdate() != 0) {
            strRet = callableStatement.getString(1);
        }
        String[] ret = strRet.split("\\^");
        return ret;
    }
}
